package com.codegeek.project.common;

import com.codegeek.common.utils.StringUtils;
import com.codegeek.common.utils.file.FileUploadUtils;
import com.codegeek.common.utils.file.FileUtils;
import com.codegeek.framework.config.RuoYiConfig;
import com.codegeek.framework.config.ServerConfig;
import com.codegeek.framework.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 *
 * @author codegeek
 */
@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private final String goBack = "../";
    private final String blank = " ";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;
            if (filePath.indexOf(goBack) != -1 || filePath.indexOf(blank) != -1) {
                throw new Exception("文件路径非法，不允许存在../或者空格");
            }


            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            if (isValidFileName(fileName)) {
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            }
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    public static boolean isValidFileName(String fileName) {
        if (fileName == null || fileName.length() > 255) {
            return false;
        } else {
            return fileName.matches("[^\\\\s\\\\\\\\/:\\\\*\\\\?\\\\\\\"<>\\\\|](\\\\x20|[^\\\\s\\\\\\\\/:\\\\*\\\\?\\\\\\\"<>\\\\|])" +
                    "*[^\\\\s\\\\\\\\/:\\\\*\\\\?\\\\\\\"<>\\\\|\\\\.]$");
        }
    }


//    public static String byteArrayToStr(byte[] byteArray) {
//        if (byteArray == null) {
//            return null;
//        }
//        String str = new String(byteArray);
//        return str;
//    }
//
//    public static boolean isFile(InputStream inputStream) throws IOException {
//        byte[] byteArray = IOUtils.toByteArray(inputStream);
//        String str = byteArrayToStr(byteArray);
//        // 匹配16进制中的 <% ( ) %>
//        // 匹配16进制中的 <? ( ) ?>
//        // 匹配16进制中的 <script | /script> 大小写亦可
//        // 通过匹配十六进制代码检测是否存在木马脚本
//        String pattern = "(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)";
//        Pattern mPattern = Pattern.compile(pattern);
//        Matcher mMatcher = mPattern.matcher(str);
//
//        // 查找相应的字符串
//        boolean flag = true;
//        if(mMatcher.find()) {
//            flag = false;
//            //过滤java关键字(java import String print write( read() php request alert system)（暂时先这样解决，这样改动最小，以后想后更好的解决方案再优化）
//            String keywordPattern = "(6a617661)|(696d706f7274)|(537472696e67)|(7072696e74)|(777269746528)|(726561642829)|(706870)|(72657175657374)|(616c657274)|(73797374656d)";
//            Pattern keywordmPattern = Pattern.compile(keywordPattern);
//            Matcher keywordmMatcher = keywordmPattern.matcher(str);
//            if(keywordmMatcher.find()){
//                flag = false;
//            }
//        }
//        return flag;
//    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
//            if (isFile(file.getInputStream())) {
//                throw new Exception("Silly, keep sending the wrong file");
//            }
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            if (filePath.indexOf(goBack) != -1 || filePath.indexOf(blank) != -1) {
                throw new Exception("文件路径非法，不允许存在../或者空格");
            }
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
